package com.group01.community.config;

import com.group01.community.constant.Constants;
import com.group01.community.entity.vo.SysUserTokenVo;
import com.group01.community.utils.*;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : iuoly
 * date : 2022/6/28
 */
@Slf4j
public class LoginSuccessHandle implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        User user = (User) authentication.getPrincipal();
        // 获取用户名，生成token
        String token = JwtUtil.generateToken(user.getUsername(), RsaUtil.privateKey, JwtUtil.EXPIRE_MINUTES);
        //将token 发送给前端
        SysUserTokenVo sysUserTokenVo = new SysUserTokenVo(user.getUsername(), token);
        ResponseResult.write(httpServletResponse, ResponseResult.ok(sysUserTokenVo));
        log.info("user:{}  token:{}", user.getUsername(), token);
        //记录登录信息
        AsyncFactory.recordLogininfor(user.getUsername(), Constants.LOGIN_SUCCESS, ResponseStatus.LOGIN_SUCCESS.getMessage());
    }
}
